﻿using MySqlX.XDevAPI.Relational;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using OfficeOpenXml;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace AoYing_DeviceCollection
{
    public class BaseUtils
    {
        public static EventMsg _eventMsg = new EventMsg();

        public static LuWenCollFile _luwen = new LuWenCollFile();

        public static JinHeAnalysis _jinhe = new JinHeAnalysis();

        #region 连接共享文件夹
        public static void ConnectState(string path, string userName, string password)
        {



            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe"; //程序调用cmd执行命令
                proc.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
                proc.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
                proc.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
                proc.StartInfo.RedirectStandardError = true; //重定向标准错误输出
                proc.StartInfo.CreateNoWindow = true; //不显示程序窗口
                proc.Start();
                string dosLine = "net use " + path + " " + password + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine); //向cmd窗口发送输入信息
                proc.StandardInput.WriteLine("exit");
                //proc.StandardInput.WriteLine(dosLine + "&exit");
                //向标准输入写入要执行的命令。这里使用&是批处理命令的符号，表示前面一个命令不管是否执行成功都执行后面(exit)命令，
                //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令，后者表示必须前一个命令执行失败才会执行后面的命令
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd(); //获取cmd窗口的输出信息，如果前面不执行exit命令，这里调用ReadToEnd()方法会假死
                proc.StandardError.Close();
                if (!string.IsNullOrEmpty(errormsg))
                {
                    throw new Exception(errormsg);
                }


            }
            catch (Exception ex)
            {


            }
            finally
            {
                proc.WaitForExit();//等待程序执行完退出进程
                proc.Close();
                proc.Dispose();
            }
        }
        #endregion

        #region 关闭共享文件夹

        public static void DisconnectNetworkDrive(string networkDrive)
        {
            Process proc = new Process();

            try
            {
                proc.StartInfo.FileName = "net";
                proc.StartInfo.Arguments = $"use {networkDrive} /delete";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();

                // 等待命令执行完毕
                proc.WaitForExit();

                // 获取命令输出
                string output = proc.StandardOutput.ReadToEnd();

                // 处理输出，检查是否有错误
                if (!string.IsNullOrWhiteSpace(output) && output.ToLower().Contains("error"))
                {
                    throw new Exception(output);
                }
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
        }


        /// <summary>
        /// 获取路径文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static FileInfo[] GetExcelDicList(string path, string fileType)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            return root.GetFiles(fileType, SearchOption.TopDirectoryOnly);
        }

        public static FileInfo[] GethtmlList(string path, string fileType)
        {
            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException($"指定的目录不存在: {path}");
            }
            return Directory.EnumerateFiles(path, fileType, SearchOption.AllDirectories)
                           .Where(f => Path.GetFileName(f).Length > 28)
                           .Select(f => new FileInfo(f))
                           .ToArray();


        }
        public static string GetThreeLevelsUpDirectory(FileInfo file)
        {
            if (file?.Directory == null) return string.Empty;
            DirectoryInfo parent = file.Directory;
            DirectoryInfo parent1 = file.Directory.Parent;      // 上一层
            DirectoryInfo parent2 = parent1?.Parent;           // 上二层
            DirectoryInfo parent3 = parent2?.Parent;            // 上三层

            return Path.Combine(parent3.Name, parent2.Name, parent1.Name, parent.Name); 
        }
        public static FileInfo GetExcelDicListMK(string path, string fileType)
        {
            DirectoryInfo root = new DirectoryInfo(path);

            // 获取所有文件并过滤掉文件名包含"良品率"的文件
            FileInfo[] allFiles = root.GetFiles(fileType, SearchOption.TopDirectoryOnly);

            // 使用 LINQ 过滤掉文件名包含 "良品率" 的文件
            FileInfo filteredFile = allFiles.FirstOrDefault(file => !file.Name.Contains("良品率"));

            return filteredFile;

        }
        public static DataTable CsvToDataTable(string fileName, string GetEncod = "GBK")
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            //StreamReader sr = new StreamReader(fs, Encoding.Default);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding(GetEncod));
            string strLine;   //记录每次读取的一行记录
            string[] aryLine;  //记录每行记录中的各字段内容
            int columnCount; //标示列数      
            bool IsFirst = false;    //标示是否是读取的第一行
            bool IsTotalResult = false;
            bool Col = true;
            try
            {  //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    if (strLine == "" || strLine.Replace(",", "") == string.Empty)
                    {
                        continue;
                    }
                    aryLine = strLine.Replace(" ", "").Split(',');
                    if (IsFirst == true)
                    {
                        IsFirst = false;
                        columnCount = aryLine.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            DataColumn dc = new DataColumn(i.ToString());
                            dt.Columns.Add(dc);
                        }
                    }
                    else
                    {
                        columnCount = aryLine.Length;
                        if (Col)
                        {

                            //创建列
                            for (int i = 0; i < 30; i++)
                            {
                                if (IsTotalResult == false) { }
                                DataColumn dc = new DataColumn(i.ToString());
                                dt.Columns.Add(dc);
                            }
                            Col = false;
                        }

                        DataRow dr = dt.NewRow();

                        for (int j = 0; j < columnCount; j++)
                        {
                            if (aryLine.Count() > j)
                            {
                                string colvalue = aryLine[j].Trim();
                                dr[j] = colvalue;
                            }

                        }
                        dt.Rows.Add(dr);
                    }

                }
            }
            catch (Exception)
            {
                throw;
            }
            sr.Close();
            fs.Close();

            // dt.Rows.Remove(dt.Rows[0]);
            return dt;
        }
        public static DataTable ReadXlsToDataTable(string filePath)
        {
            DataTable dt = new DataTable();

            // 打开 Excel 文件
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 创建 Excel 文件工作簿对象
                HSSFWorkbook workbook = new HSSFWorkbook(fs);
                // 获取第一个工作表
                ISheet sheet = workbook.GetSheetAt(0);

                // 获取工作表的第一行（表头）
                IRow headerRow = sheet.GetRow(0);
                int cellCount = headerRow.Cells.Count;

                // 给 DataTable 添加列
                for (int i = 0; i < cellCount; i++)
                {
                    dt.Columns.Add(headerRow.GetCell(i).ToString());
                }

                // 读取数据行
                for (int i = 1; i <= sheet.LastRowNum; i++)  // 从第 2 行开始（索引 1）
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = dt.NewRow();

                    for (int j = 0; j < cellCount; j++)
                    {
                        if (row != null && row.GetCell(j) != null)
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }

                    dt.Rows.Add(dataRow);
                }
            }

            return dt;
        }

    }
    #endregion

    public class EventMsg
    {
        public bool UseManualWocode { get; set; } = false;

        /// <summary>
        /// 工序-SPI/AOI
        /// </summary>
        public string LogProcess { get; set; }

        /// <summary>
        /// 制令单
        /// </summary>
        public string LogSfcno { get; set; }

        /// <summary>
        /// 工单
        /// </summary>
        public string LogWOCode { get; set; }

        /// <summary>
        /// 产品名
        /// </summary>
        public string LogMesProduct { get; set; }

        /// <summary>
        /// 产品ID
        /// </summary>
        public string LogMesProductId { get; set; }

        /// <summary>
        /// 操作步骤
        /// </summary>
        public string LogOperationStep { get; set; }

        /// <summary>
        /// 操作人
        /// </summary>
        public string Operator { get; set; }

        /// <summary>
        /// 操作人ID
        /// </summary>
        public string OperateId { get; set; }

        public string devicePath { get; set; }

        public string destPath { get; set; }
        public string HistoryFileName { get; set; }
        public string Company { get; set; }

        private string _eventMsg { get; set; }

        public string Info { get { return _eventMsg; } set { _eventMsg = value; OnTInfo(); } }

        public event EventHandler InfoHandler;

        private void OnTInfo()
        {
            if (InfoHandler != null)
            {
                InfoHandler(this, EventArgs.Empty);
            }
        }

        private string _runMsg;

        public string RunInfo { get { return _runMsg; } set { _runMsg = value; OnTRunInfo(); } }

        public event EventHandler RunInfoHandler;

        private void OnTRunInfo()
        {
            if (RunInfoHandler != null)
            {
                RunInfoHandler(this, EventArgs.Empty);
            }
        }

        private string _errorMsg;

        public string ErrorMsg { get { return _errorMsg; } set { _errorMsg = value; OnTError(); } }

        public event EventHandler ErrorMsgHandler;

        private void OnTError()
        {
            if (ErrorMsgHandler != null)
            {
                ErrorMsgHandler(this, EventArgs.Empty);
            }
        }
    }

    public class LuWenCollFile
    {
        /// <summary>
        /// 采集规则-文件关键字
        /// </summary>
        public string fileKey { get; set; }

        /// <summary>
        /// 成功目录关键字
        /// </summary>
        public string Success_FolderKey { get; set; }

        /// <summary>
        /// 采集规则-目标路径
        /// </summary>
        public string destPath { get; set; }

        /// <summary>
        /// 采集规则-异常路径
        /// </summary>
        public string exceptionPath { get; set; }

        /// <summary>
        /// 采集规则-远程用户名
        /// </summary>
        public string remoteUserName { get; set; }

        /// <summary>
        /// 采集规则-远程密码
        /// </summary>
        public string remotePassword { get; set; }

        /// <summary>
        /// 炉温-线边
        /// </summary>
        public string luwenLine { get; set; }

        /// <summary>
        /// 炉温-文件采集路径
        /// </summary>
        public string collFilePath { get; set; }

    }

    /// <summary>
    /// 奥英采集
    /// </summary>
    public class JinHeAnalysis
    {
        public string machcode { get; set; }
        /// <summary>
        /// 文件采集路径
        /// </summary>
        public string analysisPath { get; set; }

        /// <summary>
        /// 文件存放目标路径
        /// </summary>
        public string destPath { get; set; }

        /// <summary>
        /// 文件异常路径
        /// </summary>
        public string exceptionPath { get; set; }

        /// <summary>
        /// 采集规则-远程用户名
        /// </summary>
        public string remoteUserName { get; set; }

        /// <summary>
        /// 采集规则-远程密码
        /// </summary>
        public string remotePassword { get; set; }

    }

}
